package com.example.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

import com.example.service.service.MyBindService;
import com.example.service.service.MyService;

public class MainActivity extends AppCompatActivity {

    private MyBindService.MyBinder myBinder  = null;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyBindService.MyBinder)service;
            myBinder.test();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startMyService(View view) {  //启动Service
        Intent intent  = new Intent(this, MyService.class);
        startService(intent);//非绑定式
    }

    public void startMyBindService(View view) {  //启动绑定式Service
        Intent intent = new Intent(this, MyBindService.class);
        //conn是Service和Activity的连接
        bindService(intent,conn,BIND_AUTO_CREATE);  //自带方法
    }

    public void stopMyService(View view) { //停止Service
        Intent intent  = new Intent(this, MyService.class);
        stopService(intent);//非绑定式
    }

    public void stopMyServiceBymyself(View view) { //停止Service  调用stopSelf停止
        Intent intent  = new Intent(this, MyService.class);
        intent.putExtra("key_stop","stop");
        startService(intent);//非绑定式
    }
}